package com.flyim.framework.netty;

import com.alibaba.fastjson.JSONObject;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class IMHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {


    // 客户端连接建立时触发
    @Override
    public void channelActive(ChannelHandlerContext ctx) {
        log.info("客户端连接建立: {}", ctx.channel());
//        String userId = ShiroUtils.getUserId().toString();
//        // 用户上线
//        ChannelManager.bindUser(userId, ctx.channel());
//        broadcastOnlineStatus(userId, true);
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) {
        log.info("客户端连接断开: {}", ctx.channel());
//        // 用户下线
//        ChannelManager.removeChannel(ctx.channel());
//        String userId = ShiroUtils.getUserId().toString();
//        broadcastOnlineStatus(userId, false);
    }

    private void broadcastOnlineStatus(String userId, boolean isOnline) {
        JSONObject message = new JSONObject();
        message.put("type", "status");
        message.put("userId", userId);
        message.put("online", isOnline);
        ChannelManager.broadcast(message.toJSONString());
    }

    /**
     * 处理客户端消息
     * @param ctx
     * @param msg
     */
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) {
        String message = msg.text();
        log.info("收到客户端消息: {}", message);
        JSONObject json = JSONObject.parseObject(message);
        String type = json.getString("type");

        // 根据消息类型分发处理
        if ("auth".equals(type)) {
            // 身份认证
            handleAuth(ctx, json);
        } else if ("chat".equals(type)) {
            // 聊天消息
            handleChat(json, ctx);
        }
    }

    private void handleAuth(ChannelHandlerContext ctx, JSONObject json) {
        String userId = json.getString("userId");

        if (userId != null) {
            // 绑定用户ID到 Channel
            ChannelManager.bindUser(userId, ctx.channel());
            // 广播在线状态
            broadcastOnlineStatus(userId, true);
        } else {
            ctx.close(); // 认证失败则关闭连接
        }
    }

    private void handleChat(JSONObject json, ChannelHandlerContext ctx) {
        // 消息转发到对应的用户
        String toUserId = json.getString("to");
        String content = json.getString("content");
        long timestamp = json.getLongValue("timestamp");

        // 获取当前用户的 Channel
        io.netty.channel.Channel senderChannel = ctx.channel();
        // 发送者ID
        String fromUserId = ChannelManager.getUserIdByChannel(senderChannel);

        // 构建转发消息
        JSONObject forwardMessage = new JSONObject();
        forwardMessage.put("type", "chat");
        // 发送者ID
        forwardMessage.put("from", fromUserId);
        // 消息内容
        forwardMessage.put("content", content);
        // 时间戳
        forwardMessage.put("timestamp", timestamp);

        // 查找目标用户的 Channel
        Channel targetChannel = ChannelManager.getChannel(toUserId);

        if (targetChannel != null) {
            // 目标用户在线，直接转发消息
            targetChannel.writeAndFlush(new TextWebSocketFrame(forwardMessage.toJSONString()));
        } else {
            // 目标用户离线，存储消息到数据库（可选）
//            saveOfflineMessage(toUserId, forwardMessage);
        }


    }


}